using System;
using System.Text.RegularExpressions;

namespace AltNetHispano.Vale
{
	public static class CommonValidators
	{
		public static string StringIsRequired(this IValidator validator, string propertyFriendlyName, string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return string.Format("{0} is required.", propertyFriendlyName);
			}
			return string.Empty;
		}

		public static string StringLen(this IValidator validator, string propertyFriendlyName, string value, int maxlen)
		{
			if (!string.IsNullOrEmpty(value) && value.Length > maxlen)
			{
				return string.Format("{0} is too long.", propertyFriendlyName);
			}

			return string.Empty;
		}

		public static string DateIsInThePast(this IValidator validator, string propertyFriendlyName, DateTime value)
		{
			if (value.Date >= DateTime.Today)
			{
				return string.Format("{0} should be in the past.", propertyFriendlyName);
			}
			return string.Empty;
		}

		private static readonly Regex EmailRegex =
			new Regex(
				@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");

		public static string IsEmail(this IValidator validator, string propertyFriendlyName, string value)
		{
			if (!string.IsNullOrEmpty(value) && !EmailRegex.IsMatch(value)) //TODO : should check real e-mail
			{
				return string.Format("{0} is not an e-mail.", propertyFriendlyName);
			}
			return string.Empty;
		}

        public static string RegExMatch(this IValidator validator, string propertyFriendlyName, string regExPattern, string value)
        {
            if (string.IsNullOrEmpty(regExPattern))
                throw new ArgumentNullException("regExPattern");

            if(!string.IsNullOrEmpty(value) && !new Regex(regExPattern).IsMatch(value))
            {
                return string.Format("{0} is not valid", propertyFriendlyName);
            }
            return string.Empty;
        }
	}
}